<?php
namespace Orx\Mailer;
/**
 * Mail Box Object
 *
 * This object maintain the configuration parameters of a mail box
 * (connection user, password, host...)
 *
 */
class MailBox {

	/**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	const IMAP = 'imap';
	
	/**
	 * Email Server
	 * @var string
	 */
	protected $host = null;

	/**
	 * Port
	 * @var string
	 */
	protected $port = null;

	/**
	 * User/Login
	 * @var string
	 */
	protected $user = null;

	/**
	 * Password
	 * @var string
	 */
	protected $password = null;
	
	/**
	 * Mail Box Handler
	 */
	protected $handler = null;
	
	/**
	 * Use SSL
	 */
	protected $ssl = null;
	
	/**
	 * Constructor
	 */
	public function __construct($host,$port,$user,$password,$ssl = false) {
		$this->host = $host;
		$this->port = $port;
		$this->user = $user;
		$this->password = $password;
		$this->ssl = $ssl;
	}

	/**
	 * Connection to the server
	 */
	public function handle() {
		// TO BE OVERWRITTEN
		/*
		if(empty($this->handler)) {
			$this->handler = new \Zend_Mail_Storage_Imap(array(
								'host' => $this->host,
                                'user' => $this->user,
                                'password' => $this->password,
								'ssl' => $ssl
					));
		}
		return $this->handler;
 		*/
	}

	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $msgNumber
	 */
	public function read($msgNumber) {
		$email = $this->message($msgNumber);
		if(!empty($email)) {
			$data['subject'] = $email->subject;
			$data['mailto'] = $email->to;
			$data['mailfrom'] = $email->from;
		//	$data['mailfromname'] = 
			$data['body'] = $email->getContent();
			//$data['attached'] = 
			$data['senton'] = $email->date;
			$orxMail = new \Fox\Mail();
			$orxMail->setFields($data);
			return $orxMail;
		}
	}
	/**
	 * Count Number of message
	 * @return int
	 */
	public function count() {
		return 	$this->handle()->countMessages();
	}

	/**
	 * Get Messages
	 * @return Mail
	 */
	public function message($id) {
		return 	$this->handle()->getMessage($id);
	}
	
	/**
	 * Class name of the object
	 *
	 * @return string The object's class name
	 */
	public static function className() {
		return get_called_class();
	}
	
	/**
	 * Check if the folder exists
	 * @throws Zend_Mail_Storage_Exception if the current folder cannot be restored.
	 */
	public function isFolder($name) {
	    $result  = true;
	    $oldFolder = $this->handle()->getCurrentFolder();
	    try {
	        $this->handle()->selectFolder($name);
	    } catch (\Zend_Mail_Storage_Exception $e) {
	        $result = false;
	    }
	    $this->handle()->selectFolder($oldFolder);
	    return $result;
	}
}